<?php

defined('BASEPATH') or die('forbidden');

class Admin_Controller Extends Controller {

    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
    }

    function index() {
        set_area_list_view("flexigridarealist");
        $this->view->display("role/admin/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        $rows = array();
        if ($this->auth->fields['role_rank'] < 100) {
            $role = get_role_data($this->auth->fields['role_id']);
            $ids = array(0);
            foreach ($role as $m => $n) {
                $ids[] = $n['id'];
            }
            $where .= " AND role_id IN ('" . (implode("','", $ids)) . "')";
        }
        $sql = "SELECT COUNT(*) AS num FROM {pre}admin a LEFT JOIN {pre}role r ON a.role_id=r.id WHERE {$where}";
        $one = $this->db->one($sql);
        $total = $one['num'];
        $orderby = $sortname ? "ORDER BY {$sortname} {$sortorder} " : "";
        $this->db->query("SELECT {$colsinfo} FROM {pre}admin a LEFT JOIN {pre}role r ON a.role_id=r.id WHERE {$where} {$orderby} LIMIT {$offset},{$rp}");
        while ($n = $this->db->get_array('default', MYSQL_NUM)) {
            get_datetime(array(&$n[5], &$n[6]));
            $rows[] = array('id' => $n[0], 'cell' => array_values($n));
        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );
        echo json_encode($result);
    }

    function check_level($role_id) {
        if ($this->auth->fields['role_rank'] == 100)
            return true;
        $role = $this->db->one("SELECT * FROM {pre}role WHERE id='{$role_id}'");
        if ($role && $this->auth->fields['role_rank'] >= $role['rank']) {
            return true;
        } else {
            return false;
        }
    }

    function add($id = 0) {

        if (is_submit()) {
            $rowdata = $_POST['row'];
            $one = $this->db->one("SELECT * FROM {pre}admin WHERE username='{$rowdata['username']}' ");
            if (is_array($one))
                error(translate('ROLE_ADMIN_USERNAME_EXISTED', $rowdata['username']));
            $rowdata['createtime'] = time();
            $rowdata['logintime'] = time();
            $rowdata['password'] = md5($rowdata['password']);
            $rowdata['id'] = get_uuid();
            if (!$this->check_level($rowdata['role_id'])) {
                error(translate('C_INSUFFICIENT_PERMISSIONS'));
            }

            $id = $this->db->insert("{pre}admin", $rowdata);
            insert_log(translate('MENU_ROLE_ADMIN'),translate('ADD'), $rowdata);
            set_async_data($_POST['areaIds'], translate('ROLE_ADMIN_LOG_ADD', $rowdata['username']), __CLASS__, __FUNCTION__, $rowdata);
            cp_tips("success", $id);
        }
        $row = array();
        $roledata = array('' => translate('ROLE_SELECT_GROUP'));
        $role = get_role_data($this->auth->fields['role_id']);
        foreach ($role as $value)
            $roledata["{$value['id']}"] = $value['name'];

        $row['rolelist'] = $this->form->select('row[role_id]', $roledata, $row['role_id'], array('id' => 'role_id'));
        set_area_list_view("arealist");
        $this->view->display("role/admin/add", $row);
    }

    function edit($id = 0) {
        if ($id === 0)
            error(translate('C_INVALID_PARAM_ID', $id));
        $row = $this->db->one("SELECT * FROM {pre}admin WHERE id='{$id}'");
        if (!is_array($row))
            error(translate('C_INVALID_PARAM_ID', $id));
        //是否显示权限修改列表
        $role = $this->auth->get_role($row['role_id']);
        $row['showrank'] = $this->check_level($role['rank']) ? true : false;

        if (is_submit()) {
            $rowdata = $_POST['row'];
            $one = $this->db->one("SELECT * FROM {pre}admin WHERE username='{$rowdata['username']}' AND id!='{$id}'");
            if (is_array($one))
                error(translate('ROLE_ADMIN_USERNAME_EXISTED', $rowdata['username']));
            //判断权限
            if (isset($rowdata['role_id'])) {
                if (!$row['showrank']) {
                    error(translate('C_INSUFFICIENT_PERMISSIONS'));
                } else {
                    if (!$this->check_level($rowdata['role_id'])) {
                        error(translate('C_INSUFFICIENT_PERMISSIONS'));
                    }
                }
            }
            if ($rowdata['password'] != '') {
                $rowdata['password'] = md5($rowdata['password']);
            } else {
                unset($rowdata['password']);
            }

            $result = $this->db->update("{pre}admin", $rowdata, array('id' => $id));
            if ($result) {
                $rowdata['id'] = $row['id'];
                insert_log(translate('MENU_ROLE_ADMIN'),translate('EDIT'),$row, $rowdata);
                set_async_data($_POST['areaIds'], translate('ROLE_ADMIN_LOG_EDIT', $rowdata['username']), __CLASS__, __FUNCTION__, $rowdata);
            }
            cp_tips("success", $id);
        }
        $roledata = array('' => translate('ROLE_SELECT_GROUP'));
        $role = get_role_data($this->auth->fields['role_id']);
        foreach ($role as $value)
            $roledata["{$value['id']}"] = $value['name'];

        $row['rolelist'] = $this->form->select('row[role_id]', $roledata, $row['role_id'], array('id' => 'role_id'));
        set_area_list_view("arealist");
        $this->view->display("role/admin/edit", array('row' => $row));
    }

    function del($id = 0) {
        $c = 0;
        $r = '';
        if ($id === 0)
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        $row = $this->db->one("SELECT * FROM {pre}admin WHERE id='{$id}'");
        if (!is_array($row)) {
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        } else {
            if ($id != $this->auth->user_id) {
                if ($id != '71830689-c2e6-43b1-a3fe-b9dcaf5d8662') {
                    if ($this->check_level($id)) {
                        if ($this->db->delete('{pre}admin', array('id' => $id))) {
                            insert_log(translate('MENU_ROLE_ADMIN'),translate('DEL'), $row);
                            $c = 1;
                            $r = set_async_data($_POST['areaIds'], translate('ROLE_ADMIN_LOG_DEL', $row['username']), __CLASS__, __FUNCTION__, array('id' => $row['id']), true);
                        } else {
                            $r = translate('C_TIPS_ERROR_TEXT');
                        }
                    } else {
                        $r = translate('C_INSUFFICIENT_PERMISSIONS');
                    }
                } else {
                    $r = translate('ROLE_ADMIN_SUPER_ADMIN_COULD_NOT_DEL');
                }
            } else {
                $r = translate('ROLE_ADMIN_COULD_NOT_DEL_SELF');
            }
        }
        json_output($c, $r);
    }

    function multi() {
        $type = $this->input->post("type");
        $ids = $this->input->post("ids");
        $c = 0;
        $r = '';
        if (count(explode(',', $ids)) == 0) {
            $r = translate('C_INVALID_PARAMS');
        } else {
            $ids = explode(',', $ids);           
            if ($type == 'delete') {
               foreach ($ids as $value)
               {
               	$this->del($value);
               	$r=translate('SUCCESS');
               }
            } else {
                $r = translate('C_INVALID_PARAMS');
            }
        }
        json_output($c, $r);
    }

}